import axios from 'axios';
import { msgline, msglog } from '../display/ui/MsgLines';
import { ComboBox } from '../display/eui/ComboBox';
var md5 = require('md5');

export class DlgLogin extends eui.Component{

    constructor(){
        super();
        this.skinName = "loginSkin";
    }

    inputAccount:eui.TextInput;
    inputPassword:eui.TextInput;
    btnLogin:eui.Button;
    cbServers:ComboBox;

    childrenCreated():void{
        super.childrenCreated();
        let user = egret.localStorage.getItem("login.account")
        if (user){
            this.inputAccount.text = user;
        }
        this.btnLogin.addEventListener("touchTap",this.onLogin,this);
        this.cbServers.setValues(["http://localhost:8081/api/"]);
    }

    onLogin(){
        let account = this.inputAccount.text;
        let pw = this.inputPassword.text;
        if (account === '' || pw === ''){
            msgline("acount or pw is null")
            return ;
        }
        let server = this.cbServers.getValue();
        if (!server){
            msgline("server is null")
            return;
        }
        this.login(server,account,pw);
    }

    account : string;

    async login(baseURL: string, account:string,pw:string){
        let instance = axios.create({
            //baseURL:"http://localhost:8081/api/",
            baseURL,
            timeout: 1000,
        });
        try {
            let password = md5(pw);
            let res = await instance.post("/login",{account,password})
            console.log("login rt",res.data);
            if (res.data.rt === 1){
                msgline("login ok")
                this.account = account;
                egret.localStorage.setItem("login.account",account)
            }
            else {
                msglog("login error",res.data.msg)
            }
        }
        catch(error){
            msglog("http error",error)
            console.error(error);
        }
    }
}